<template>
  <div class="createrOrder-box">
    <div class="header">
      <h5>{{ props.isShenpi ? '审批' : props.OrderUpdateTitle }}</h5>
      <i class="iconfont icon-close" @click="closeUptatePop"></i>
    </div>
    <div class="createrOrder-main">
      <el-form
        ref="ruleFormRef"
        style="width: 100%"
        :model="rowDataUpdate"
        label-width="auto"
        class="demo-rowDataUpdate"
        :size="formSize"
        status-icon
        scroll-to-error
      >
        <div class="item-list">
          <el-form-item label="单号：" class="code" required style="min-width: 200px">
            <span style="min-width: 200px">{{ rowDataUpdate.orderId }}</span>
          </el-form-item>
          <el-form-item label="终端门店">
            <el-input v-model="rowDataUpdate.customerStore" :disabled="disabledFlagOuter" />
          </el-form-item>
          <el-form-item label="客户名称">
            <!-- <el-select v-model="rowDataUpdate.customerName" >

                        </el-select> -->
            <el-select
              v-model="rowDataUpdate.customerName"
              placeholder="请输入客户名称"
              filterable
              popper-class="departmentSelect"
              @change="customerChange"
              :disabled="disabledFlagOuter"
            >
              <el-option
                v-for="item in customerList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="联系人" prop="contact">
            <el-input v-model="rowDataUpdate.contactPerson" :disabled="disabledFlagOuter" />
          </el-form-item>
          <el-form-item label="业务员" prop="salesman" @click="openSelectUser">
            <!-- <el-select v-model="rowDataUpdate.employeeName" popper-class="departmentSelect">
                        </el-select> -->
            <el-input v-model="rowDataUpdate.employeeName" placeholder="请选择业务员" disabled />
          </el-form-item>
          <el-form-item label="部门" prop="department">
            <el-tree-select
              v-model="rowDataUpdate.deptId"
              :data="deptOptions"
              popper-class="departmentSelect"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              placeholder="请选择归属部门"
              check-strictly
              :disabled="disabledFlagOuter"
            />
          </el-form-item>
          <el-form-item label="下单日期" required prop="startTime">
            <el-date-picker
              v-model="rowDataUpdate.orderDate"
              type="date"
              label="下单日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled="true"
            />
          </el-form-item>
          <el-form-item label="交货日期" prop="endTime">
            <el-date-picker
              v-model="rowDataUpdate.deliveryDate"
              type="date"
              label="交货日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled="disabledFlagOuter"
            />
          </el-form-item>
          <el-form-item label="票据类型" prop="bill">
            <el-select v-model="rowDataUpdate.invoiceType" :disabled="disabledFlagOuter">
              <el-option label="增值税发票" value="增值税发票" />
              <el-option label="普通发票" value="普通发票" />
            </el-select>
          </el-form-item>
          <el-form-item label="后期服务" prop="server">
            <el-select v-model="rowDataUpdate.afterSalesService" :disabled="disabledFlagOuter">
              <el-option label="上门安装" value="上门安装" />
              <el-option label="送货上门" value="送货上门" />
              <el-option label="自取" value="自取" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户累计应收款" prop="crediting">
            <el-input
              v-model="rowDataUpdate.customerCumulativeAmount"
              :disabled="disabledFlagOuter"
            />
          </el-form-item>
          <el-form-item label="回款周期" prop="crediting">
            <el-date-picker
              v-model="rowDataUpdate.paymentDate"
              type="date"
              :disabled="rowDataUpdate.successStatus !== '已完工'"
              label="下单日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </div>
        <!-- 表格 -->
        <EditTable
          :boder="true"
          :dataTable="rowDataUpdate.productionVOS"
          @excelTable="excelTable"
          @createTable="createTable"
          @deleteRow="deleteRow"
          :disabledFlagOuter="disabledFlagOuter"
        />
        <div class="item-list2">
          <el-form-item label="预算成本：" prop="cost" class="cost-box">
            <div class="list">
              <p>预算材料费</p>
              <el-input v-model="rowDataUpdate.materialFeeTotal" :disabled="disabledFlagOuter" />
            </div>
            <div class="list">
              <p>预算安装费</p>
              <el-input
                v-model="rowDataUpdate.installationFeeTotal"
                :disabled="disabledFlagOuter"
              />
            </div>
            <div class="list">
              <p>预算城管费</p>
              <el-input v-model="rowDataUpdate.urbanManagementFee" :disabled="disabledFlagOuter" />
            </div>
          </el-form-item>
          <el-form-item label="实际成本：" class="cost-box">
            <div class="list">
              <p>实际材料费</p>
              <el-input v-model="rowDataUpdate.actualTotalMaterial" disabled type="Number" />
            </div>
            <div class="list">
              <p>实际安装费</p>
              <el-input v-model="rowDataUpdate.actualTotalInstall" type="Number" />
            </div>
            <div class="list">
              <p>实际城管费</p>
              <el-input v-model="rowDataUpdate.actualUrbanManagementFee" type="Number" />
            </div>
          </el-form-item>
          <!-- <div class="list">
                        <p>优惠金额</p>
                        <el-input v-model="rowDataUpdate.discount" />
                    </div> -->
          <el-form-item label="订单总金额：" prop="totalMoney">
            <el-input v-model="rowDataUpdate.totalOrderAmount" disabled class="totalMoney-input" />
            <!--            :disabled="disabledFlagOuter"-->
          </el-form-item>
          <el-form-item label="结款状态：" prop="paymentStatus">
            <el-input v-model="rowDataUpdate.invoiceStatus" :disabled="disabledFlagOuter" />
          </el-form-item>
          <el-form-item label="客户类型：" prop="clienttype">
            <el-select v-model="rowDataUpdate.customerType" :disabled="disabledFlagOuter">
              <el-option label="标准流程" value="标准流程" />
              <el-option label="外协流程" value="外协流程" />
              <el-option label="散客" value="散客" />
            </el-select>
          </el-form-item>

          <el-form-item label="备注：" prop="desc">
            <el-input
              v-model="rowDataUpdate.remarks"
              type="textarea"
              :disabled="disabledFlagOuter"
            />
          </el-form-item>
          <el-form-item label="制单人：" prop="made">
            <el-input v-model="rowDataUpdate.creator" :disabled="disabledFlagOuter" />
          </el-form-item>
          <el-form-item label="审批人：" prop="approval">
            <el-input v-model="rowDataUpdate.approver" :disabled="disabledFlagOuter" />
          </el-form-item>
        </div>
        <div class="tableUtils" v-if="props.isShenpi">
          <el-button @click="isPass(1)" class="create"> 通过 </el-button>
          <el-button @click="isPass(2)" class="close">驳回</el-button>
        </div>
        <div class="tableUtils" v-else>
          <el-button @click="submitForm" class="create" v-if="props.updataFlag"> 保存 </el-button>
          <el-button @click="closeUptatePop" class="close">关闭</el-button>
        </div>
      </el-form>
    </div>
    <selectUser ref="selectRef" @userOneInfo="userOneInfo" />
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, defineEmits, defineProps } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { deptTreeSelect } from '@/api/system/user'
import { checkOrderBaoZhangApi, getWorkApi, updateOrderWanGongApi } from '@/api/tickets'
import selectUser from '@/components/allUserInfo/index'

import EditTable from '@/components/table/editTable.vue'
import { getupdateOrderApi } from '@/api/tickets/index'
const selectRef = ref(null)
const emit = defineEmits([
  'closeUptatePop',
  'setUserOneInfo',
  'updataCustomer',
  'createTable',
  'actualCostSum',
])
const props = defineProps({
  rowDataUpdate: {
    type: Object,
    default: [],
    required: true,
  },
  updataFlag: {
    type: Boolean,
    default: true,
  },
  OrderUpdateTitle: {
    type: String,
    default: '修改订单信息',
  },
  // 审批操作
  isShenpi: {
    type: Boolean,
    default: false, // 默认为编辑
  },
})
let deptOptions = ref([])
const formSize = ref('default')
const ruleFormRef = ref()
const disabledFlagOuter = ref(false)

// 修改接口
const getupdateOrderApiUpdate = async (params) => {
  let res = await getupdateOrderApi(params)
  let { code, msg } = res
  if (code == 200) {
    ElMessage.success(msg)
    emit('closeUptatePop', false)
  } else {
    ElMessage.error(msg)
  }
}
// 通过/驳回
const isPass = (type) => {
  //   type 1 通过 2 驳回
  console.log(type, 'type')
  //  orderIdList status  通过、不通 reason  原因
  ElMessageBox.prompt('请输入原因', '审批', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(async ({ value }) => {
      let params = {
        reason: value,
        status: type === 1 ? '通过' : '不通过',
        orderIdList: [props.rowDataUpdate.orderId],
      }
      console.log(params, 'params')
      let res = await checkOrderBaoZhangApi(params)
      let { code } = res
      if (code === 200) {
        ElMessage({
          type: 'success',
          message: '审批成功',
        })
        emit('closeUptatePop', false)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '用户取消',
      })
    })
}
// 修改
const submitForm = () => {
  let params = {
    orderIdAOS: [],
  }
  // props.rowDataUpdate.productionVOS.forEach((v) => {
  //     console.log(v);
  //     params.orderIdAOS.push({
  //         id: v.id,
  //         actualCost: v.actualCost
  //     })
  // });
  getupdateOrderApiUpdate(props.rowDataUpdate)
}
// 创建一行表格
const createTable = (data) => {
  emit('createTable', data)
}
const deleteRow = (v) => {
  emit('deleteRow', v)
}

// 关闭当前弹窗
const closeUptatePop = () => {
  emit('closeUptatePop', false)
}
// 导入的表格数据
const excelTable = (data) => {
  data.forEach((v) => {
    dataTable.value.push(v)
  })
}
/*查询部门下拉树结构 */
const getDeptTree = () => {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data
  })
}

let customerList = reactive([])
const customerChange = (e) => {
  let customerObj = customerList.find((v) => e == v.value)
  emit('updataCustomer', e, customerObj)
}
// 获取客户下拉菜单数据
const getWorkApiData = async (v = '') => {
  let params = { customerName: v }
  let { code, data } = await getWorkApi(params)
  if (code == 200) {
    data.forEach((v) => {
      customerList.push({
        label: v.primaryClassification + '/' + v.customerName,
        value: v.customerId,
      })
    })
  }
}
/** 打开授权用户表弹窗 */
const openSelectUser = () => {
  selectRef.value.show()
}

// 获取人员信息
const userOneInfo = (v) => {
  emit('setUserOneInfo', String(v.userIds), v.nickName)
}

onMounted(() => {
  getWorkApiData()
  getDeptTree()
  // let currentDateTime = new Date()
  // //如果props.rowDataUpdate.orderDate为7天前的日期，那么就不让修改
  // let orderDate = new Date(props.rowDataUpdate.orderDate)
  // let time = currentDateTime.getTime() - orderDate.getTime()
  // let days = time / (1000 * 60 * 60 * 24)
  // if (days > 7) {
  //     disabledFlagOuter.value = true
  // }
  // alert(days)
  if (props.rowDataUpdate.voucherStatus === '已生成') {
    disabledFlagOuter.value = true
  }
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.module.scss';

.createrOrder-box {
  width: 100%;
  height: 100%;
  padding: 0 26px;
  overflow-y: scroll;
  position: relative;
  :deep(.el-form-item__label-wrap) {
    margin-left: 0 !important;
  }
  .totalMoney-input {
    :deep(.el-input__inner) {
      font-weight: 700;
      color: #000;
    }
  }
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 4px 4px 0px 0px;
    padding: 0 30px;
    height: 40px;
    width: 100%;
    z-index: 2024;
    background: #fff;
    position: sticky;
    top: 0;

    h5 {
      color: #333;
      font-weight: 600;
      font-size: 18px;
    }

    .icon-close {
      border: 1px solid #666;
      background: #ffffff;
      border-radius: 50%;
      cursor: pointer;
      padding: 5px;
    }
  }

  .createrOrder-main {
    .el-form {
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC;

      .departmentSelect {
        .el-scrollbar {
          .el-scrollbar__view {
            width: 124px !important;

            .el-input {
              width: 100%;
              height: 20px;
            }

            .el-select-dropdown__item {
              width: 100%;
              font-size: 12px;
            }
          }
        }
      }

      .item-list,
      .item-list1 {
        display: flex;
        flex-wrap: wrap;

        .code {
          width: 162px !important;
          font-family:
            PingFang SC,
            PingFang SC;
          font-weight: 500;
          font-size: 14px;
          color: #333333;
          line-height: 0px;
          text-align: left;
          font-style: normal;
          text-transform: none;
        }

        .el-form-item {
          width: 231px;
          margin-right: 20px;

          .el-form-item__content {
            width: 100%;
          }
        }
      }

      .el-input {
        width: 128px;
      }

      .item-list2 {
        .el-form-item {
          width: 400px;

          .el-form-item__label-wrap {
            margin-left: 0 !important;

            .el-input__inner {
              width: 128px;
            }
          }
        }

        .cost-box {
          display: flex;
          align-items: center;
          width: 100% !important;

          .list {
            display: flex;
            align-items: center;

            P {
              margin-right: 15px;
              font-family:
                PingFang SC,
                PingFang SC;
              font-weight: 500;
              font-size: 14px;
              color: #333333;
              line-height: 0px;
              text-align: left;
              font-style: normal;
              text-transform: none;
              margin-left: 10px;
            }
          }
        }
      }
    }

    .tableUtils {
      padding-right: 80px;
      padding-bottom: 50px;
      width: 100%;
      text-align: right;

      .create {
        background-color: $base-btn-color;
        color: azure;
        cursor: pointer;
        width: 58px;
        height: 28px;
        box-shadow: 2px 3px 6px 1px rgba(0, 0, 0, 0.16);
        border-radius: 2px 2px 2px 2px;
        text-align: center;
        line-height: 28px;
        cursor: pointer;
      }

      .close {
        width: 58px;
        height: 28px;
        background: linear-gradient(180deg, #d8e0ff 0%, #ffffff 100%);
        box-shadow: 2px 3px 6px 1px rgba(0, 0, 0, 0.16);
        border-radius: 2px 2px 2px 2px;
        text-align: center;
        line-height: 28px;
        cursor: pointer;
      }
    }
  }
}
</style>
